#coding:utf8
import mysql_base
from sql_deal import deal_sql
from mg_config import config
import redis
class connDB(deal_sql,object):
    def __init__(self):
        self.client = mysql_base.mysqlDB(config['m_ip'],config['m_port'],config['m_user'],config['m_pwd'],config['m_db'])
        if config.get("r_password"):
            pool = redis.ConnectionPool(host = config['r_ip'],port =config['r_port'],db=config['r_db'],password =config['r_password'])
        else:
            pool = redis.ConnectionPool(host = config['r_ip'],port =config['r_port'],db=config['r_db'])
        self.r = redis.Redis(connection_pool=pool)

    def select(self,table_name,condition,field =None):
        sql,values = self.select_sql(table_name,condition, field = field,limit=1)
        items = self.client.mselect(sql,values)
        if  items:
            return items[0]
        return dict()
    ## 获取mysql游标
    def mysqlcur(self):
        return self.client.base_connect()

    def select_all(self,table_name,condition=None , field = None,offset = None, limit=None, in_condition =None, order_by = None):
        sql,values = self.select_sql(table_name,condition, field = field, offset = offset, limit=limit, in_condition = in_condition, order_by = order_by)
        return self.client.mselect(sql,values)

    def add(self,table_name,query):
        sql,values  =self.insert_sql(table_name,query)
        ret = self.client.madd(sql,values)
        return ret
    def add2(self,table_name,query):
        return self.insert_sql2(table_name,query)
    def new_add(self,conn,cur,table_name,query):
        sql,values  =self.inert_sql(table_name,query)
        ret = cur.execute(sql % values)
        last_id = 0
        if ret==1:
            last_id = int(cur.lastrowid)
        conn.commit()
        return last_id
    def addall(self,sql,values):
        self.client.malladd(sql, values)
    def delete(self, table_name,params):
        sql,values = self.delete_sql(table_name,params)
        return self.client.mdelete(sql,values)

    def update(self,table_name,query,condition):
        sql,values = self.update_sql(table_name,query,condition)
        return self.client.mupdate(sql,values)


    ## 多语句事务处理
    def trance(self,sql_list):
        success = False
        conn,cur = self.mysqlcur()
        try:
            conn.begin()
            _success = 0
            for sql,values in sql_list:
                if sql.find('INSERT')>-1:
                    cur.execute(sql % values)
                else:
                    cur.execute(sql,values)
                _success+=1
            if _success==len(sql_list):
                conn.commit()
                success = True
        except Exception as e:
            print str(e)
            conn.rollback()
        finally:
            conn.close()
            cur.close()
            return success

